#include<iostream>
#include<mysql/mysql.h>
#include<string>
#include<vector>

#define HOST "127.0.0.1"
#define USER "root"
#define PASSWORD "260504hlh@"
#define PORT 3306
#define DBNAME "gobang"



int main()
{
    //1.初始化mysql句柄
    MYSQL *mysql=mysql_init(nullptr);
    if(!mysql)
    {
        std::cout<<"初始化mysql句柄失败"<<std::endl;
        return -1;
    }
    //2.连接服务器
    //MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user,  const char *passwd,const char *db, unsigned int port,  const char *unix_socket, unsigned long client_flag);
    if(mysql_real_connect(mysql,HOST,USER,PASSWORD,DBNAME,PORT,nullptr,0)==nullptr)
    {
        std::cout<<"连接数据库失败"<<std::endl;
        std::cout<<"错误信息:"<<mysql_error(mysql)<<std::endl;
        mysql_close(mysql);
        return -1;
    }
    //3.设置客户端字符集
    //int mysql_set_character_set(MYSQL *mysql, const char *csname)
    if(mysql_set_character_set(mysql,"utf8")!=0)
    {
        std::cout<<"设置字符集失败"<<std::endl;
        std::cout<<"错误信息:"<<mysql_error(mysql)<<std::endl; 
        mysql_close(mysql);
        return -1;
    }
    //4.选择要操作的数据库
    //int mysql_select_db(MYSQL *mysql, const char *db)
    // if(mysql_select_db(mysql,DBNAME)!=0)
    // {
    //     std::cout<<"选择数据库失败"<<std::endl;
    //     std::cout<<"错误信息:"<<mysql_error(mysql)<<std::endl; 
    //     mysql_close(mysql);
    //     return -1;
    // }
    //5.执行sql语句
    //int mysql_query(MYSQL *mysql, const char *q)
    //std::string sql="insert stu values(1001,'张三',18,53,68,78)";
    //std::string sql="insert stu values(1002,'李四',18,53,68,78)";
    //std::string sql="insert stu values(1003,'王五',18,53,68,78)";
    //std::string sql="update stu set cn=cn+40 where name='张三'";
    //std::string sql="delete from stu where name='张三'";
    std::string sql="select * from stu";
    int ret =mysql_query(mysql,sql.c_str());
    if(ret!=0)
    {
        std::cout<<"执行sql语句失败"<<std::endl;
        std::cout<<"错误信息:"<<mysql_error(mysql)<<std::endl; 
        mysql_close(mysql);
        return -1;
    }
    //6.如果sql语句是查询语句,则保存查询结果到本地
    //MYSQL_RES *mysql_store_result(MYSQL *mysql)
    MYSQL_RES *res=mysql_store_result(mysql);
    if(!res)
    {
        std::cout<<"获取查询结果失败"<<std::endl;
        std::cout<<"错误信息:"<<mysql_error(mysql)<<std::endl; 
        mysql_close(mysql);
        return -1;
    }
    //7.获取查询结果的字段数和行数
    int field_count=mysql_num_fields(res);
    int row_count=mysql_num_rows(res);
    //8.遍历查询结果
    for(int i=0;i<row_count;i++)
    {
        MYSQL_ROW row=mysql_fetch_row(res);
        for(int j=0;j<field_count;j++)
        {
            std::cout<<row[j]<<"\t";
        }
        std::cout<<std::endl;
    }
    //9.释放结果集
    mysql_free_result(res);
    //10.关闭数据库连接并释放mysql句柄
    mysql_close(mysql);
    return 0;
}